<?php

// TODO - convert all localization to use the Communit.as localization system

// CONSTANTS
define("TB_BROWSE", "Browse");
define("TB_EDIT", "Edit");
define("TB_UPLOAD", "Upload");
define("TB_VIEW", "View As: ");
define("TB_SHOW", "Show: ");
define("TB_PAGE", "Page");
define("TB_FILENAME", "File Name");
define("TB_SIZE", "Size");
define("TB_DIMENSIONS", "Dimensions");
define("TB_TYPE", "Type");
define("TB_DATE", "Date Modified");
define("TB_SEARCH", "Search");
define("TB_FILES", "Files");
define("TB_BROWSEFILES", "Browse Files");
define("TB_DETAILS", "Details");
define("TB_THUMBS", "Thumbnails");
define("TB_EDITFILES", "Edit Files");
define("TB_ACTION", "Action");
define("TB_DELETE", "Delete");
define("TB_RENAME", "Rename");
define("TB_ROTATE", "Rotate");
define("TB_RESIZE", "Resize");
define("TB_UPLOADAFILE", "Upload a File");
define("TB_UPLOADFILES", "Upload Files");
define("TB_PROGRESS", "Progress");
define("TB_REMOVE", "Remove");
define("TB_BYTES", "bytes");
define("TB_WIDTH", "width");
define("TB_HEIGHT", "height");
define("TB_NONE", "None");
define("TB_TYPEIMG", "Images");
define("TB_TYPEMEDIA", "Media");
define("TB_TYPEFILE", "All Files");
define("TB_TYPEABOUTVIDEO", "About Section Videos");
define("TB_ROTATECW", "Rotate 90 degrees clockwise");
define("TB_ROTATECCW", "Rotate 90 degrees anti-clockwise");
define("TB_MSGNEWTHUMBS", "%s new image thumbnails have been generated.");
define("TB_MSGMKDIR", "The '%s' directory has been successfully created.");
define("TB_MSGMKDIRFAIL", "Unable to create the '%s' directory - please check your permissions.");
define("TB_MSGDELETE", "%s files have been successfully deleted.");
define("TB_MSGRENAME", "%s files have been successfully renamed.");
define("TB_MSGRESIZE", "%s images have been successfully resized.");
define("TB_MSGROTATE", "%s images have been successfully rotated.");
define("TB_MSGEDITERR", "%s files encountered errors during the requested operation.");
define("TB_MSGUPGOOD", "%s files have been successfully uploaded.");
define("TB_MSGUPBAD", "%s files have not been uploaded, due to security restrictions.");
define("TB_MSGUPDUP", "%s files have not been uploaded, as they already exist - please delete or rename original files.");
define("TB_MSGUPFAIL", "File upload failed - please check your permissions for '%s'.");
define("TB_MSGMAXSIZE", "cannot be queued for upload as the size exceeds the maximum limit of");
define("TB_TTLMAXSIZE", "File Size Error");
define("TB_DENIED", "You require permission to view this page.");
define("TB_UPDENIED", "You require upload permission to view this page.");
define("TB_EDDENIED", "You require edit or delete permissions to view this page.");

/*
    Class: Filebrowser_AdminController

	About: Author
		Rich Joslin <http://richjoslin.com>
		Based on TinyBrowser by Bryn Jones <http://www.lunarvis.com>
*/
class Filebrowser_AdminController extends Cts_Controller_Action_Admin {

	private $_tb_config = array();

	function init() {

		// Random string used to secure Flash upload if session control not enabled - be sure to change!
		$this->_tb_config['obfuscate'] = Cts_Registry::get('file_browser_flash_obuscation_key');

		// TODO - drive this based on the locale selected in the CMS currently
		// Set default language (ISO 639-1 code)
		$this->_tb_config['language'] = 'en';

		// Set the integration type (TinyMCE is default)
		$this->_tb_config['integration'] = 'tinymce'; // Possible values: 'tinymce', 'fckeditor'

		// Default is rtrim($_SERVER['DOCUMENT_ROOT'], '/')
		// (suitable when using absolute paths, but can be set to '' if using relative paths)
		$this->_tb_config['docroot'] = rtrim($_SERVER['DOCUMENT_ROOT'], '/');

		// Folder permissions for Unix servers only
		$this->_tb_config['unixpermissions'] = 0777;

		// TODO - this path should change based on the user and other vars passed in, like journal ID
		// File link paths - these are the paths that get passed back to TinyMCE or your application

		// TODO - pull these from the database - these are implementation-specific
		$this->_tb_config['link']['image'] = '/uploads/black-diamond/images/';
		$this->_tb_config['link']['media'] = '/uploads/black-diamond/media/';
		$this->_tb_config['link']['file'] = '/uploads/black-diamond/files/';
		$this->_tb_config['link']['about_video'] = '/uploads/black-diamond/about_videos/';
		$this->_tb_config['link']['bg_image'] = '/uploads/black-diamond/bg_images/';
		$this->_tb_config['link']['bg_image_thumb'] = '/uploads/black-diamond/bg_images/thumbs/';
		$this->_tb_config['link']['cat_thumb'] = '/uploads/black-diamond/category_thumbs/';
		$this->_tb_config['link']['header'] = '/uploads/black-diamond/headers/';

		// File upload paths
		// TODO - pull these from the database - these are implementation-specific
		$this->_tb_config['path']['image'] = $this->_tb_config['link']['image']; // automatically creates a '_thumbs' subdirectory within this path to hold the image thumbnails
		$this->_tb_config['path']['media'] = $this->_tb_config['link']['media'];
		$this->_tb_config['path']['file'] = $this->_tb_config['link']['file'];
		$this->_tb_config['path']['about_video'] = $this->_tb_config['link']['about_video'];
		$this->_tb_config['path']['bg_image'] = $this->_tb_config['link']['bg_image'];
		$this->_tb_config['path']['bg_image_thumb'] = $this->_tb_config['link']['bg_image_thumb'];
		$this->_tb_config['path']['cat_thumb'] = $this->_tb_config['link']['cat_thumb'];
		$this->_tb_config['path']['header'] = $this->_tb_config['link']['header'];

		// File upload size limit (0 is unlimited)
		$this->_tb_config['maxsize']['image'] = Cts_Registry::get('file_browser_max_size_image', 'filebrowser');
		$this->_tb_config['maxsize']['media'] = Cts_Registry::get('file_browser_max_size_media', 'filebrowser');
		$this->_tb_config['maxsize']['file'] = Cts_Registry::get('file_browser_max_size_file', 'filebrowser');
		$this->_tb_config['maxsize']['about_video'] = Cts_Registry::get('file_browser_max_size_about_video', 'filebrowser');
		$this->_tb_config['maxsize']['bg_image'] = Cts_Registry::get('file_browser_max_size_bg_image', 'filebrowser');
		$this->_tb_config['maxsize']['bg_image_thumb'] = Cts_Registry::get('file_browser_max_size_bg_image_thumb', 'filebrowser');
		$this->_tb_config['maxsize']['cat_thumb'] = Cts_Registry::get('file_browser_max_size_cat_thumb', 'filebrowser');
		$this->_tb_config['maxsize']['header'] = Cts_Registry::get('file_browser_max_size_header', 'filebrowser');

		// Image automatic resize on upload (0 is no resize)
		$this->_tb_config['imageresize']['width'] = Cts_Registry::get('file_browser_resize_image_width', 'filebrowser');
		$this->_tb_config['imageresize']['height'] = Cts_Registry::get('file_browser_resize_image_height', 'filebrowser');

		// Image thumbnail source (set to 'path' by default - shouldn't need changing)
		// Possible values: path, link
		$this->_tb_config['thumbsrc'] = 'path';

		// Image thumbnail size in pixels
		$this->_tb_config['thumbsize'] = Cts_Registry::get('file_browser_thumb_size', 'filebrowser'); // 80;

		// Image and thumbnail quality, higher is better (1 to 99)
		$this->_tb_config['imagequality'] = Cts_Registry::get('file_browser_image_quality', 'filebrowser'); // only used when resizing or rotating
		$this->_tb_config['thumbquality'] = Cts_Registry::get('file_browser_thumb_quality', 'filebrowser'); // 80;

		// Date format, as per php date function
		$this->_tb_config['dateformat'] = Cts_Registry::get('file_browser_display_date_format', 'filebrowser');

		// Permitted file extensions
		$this->_tb_config['filetype']['image'] = Cts_Registry::get('file_browser_allowed_image_extensions', 'filebrowser');
		$this->_tb_config['filetype']['media'] = Cts_Registry::get('file_browser_allowed_media_extensions', 'filebrowser');
		$this->_tb_config['filetype']['file']  = Cts_Registry::get('file_browser_allowed_other_file_types', 'filebrowser');
		$this->_tb_config['filetype']['about_video']  = Cts_Registry::get('file_browser_allowed_media_extensions', 'filebrowser');
		$this->_tb_config['filetype']['bg_image']  = Cts_Registry::get('file_browser_allowed_image_extensions', 'filebrowser');
		$this->_tb_config['filetype']['bg_image_thumb']  = Cts_Registry::get('file_browser_allowed_image_extensions', 'filebrowser');
		$this->_tb_config['filetype']['cat_thumb']  = Cts_Registry::get('file_browser_allowed_image_extensions', 'filebrowser');
		$this->_tb_config['filetype']['header']  = Cts_Registry::get('file_browser_allowed_image_extensions', 'filebrowser');

		// Prohibited file extensions
		$this->_tb_config['prohibited'] = array('ascx', 'asp', 'aspx', 'bat', 'cfc', 'cfm', 'cgi', 'com', 'conf',
			'dll', 'exe', 'ini', 'js', 'jsp', 'php', 'php3', 'php5', 'phtml', 'pl', 'py', 'reg', 'sh');

		// Default file sort
		// Possible values: name, size, type, modified
		$this->_tb_config['order']['by'] = Cts_Registry::get('file_browser_order_by', 'filebrowser');
		$this->_tb_config['order']['type'] = Cts_Registry::get('file_browser_order_direction', 'filebrowser');

		// Default image view method
		// Possible values: thumb, detail
		$this->_tb_config['view']['image'] = Cts_Registry::get('file_browser_default_view', 'filebrowser');

		// File Pagination - split results into pages (0 is none)
		$this->_tb_config['pagination'] = Cts_Registry::get('file_browser_page_size', 'filebrowser');

		// TinyMCE dialog.css file location, relative to tinybrowser.php (can be set to absolute link)
		$this->_tb_config['tinymcecss'] = Cts_Registry::get('file_browser_tiny_mce_css', 'filebrowser');

		// TODO - change these variables based on the logged-in user's permissions
		// Assign Permissions for Upload, Edit and Delete
		$this->_tb_config['allowupload'] = true;
		$this->_tb_config['allowedit'] = false;
		$this->_tb_config['allowdelete'] = true;

		// Set default action for edit page
		// Possible values: delete, rename
		$this->_tb_config['defaultaction'] = Cts_Registry::get('file_browser_default_edit_action', 'filebrowser');

		parent::init();
	}

	function cssAction() {
		header ("Content-type: text/css");
		$thumbsize                  = $this->_tb_config['thumbsize'];
		$this->view->thumbsize      = $thumbsize;
		$this->view->cell_height    = $thumbsize + 40;
		$this->view->cell_width     = $thumbsize + 25;
		$this->view->cell_width_ie  = $thumbsize + 28;
		$this->view->cell_font_size = $thumbsize;
		$this->view->filename_width = $thumbsize + 20;
	}

	function jsAction() {
		if (strpos($_SERVER['HTTP_REFERER'], 'filebrowser/admin/tinybrowser') > 0) {
			$mainpage = true;
		} else {
			$mainpage = false;
		}
		$feid_isset = isset($_GET['feid']);
		if ($feid_isset) {
			$this->view->feid = $_GET['feid'];
		}
		$this->view->mainpage = $mainpage;
		$this->view->feid_isset = $feid_isset;
		$this->view->tinybrowser = $this->_tb_config;
	}

	function tinybrowserAction() {

		// Assign get variables
		$typenow = (isset($_GET['type']) ? $_GET['type'] : 'image');

		// TODO - check if an array contains the value instead of doing this big if statement
		if (
			$typenow != "image"
			&& $typenow != "media"
			&& $typenow != "file"
			&& $typenow != "about_video"
			&& $typenow != "bg_image"
			&& $typenow != "bg_image_thumb"
			&& $typenow != "cat_thumb"
			&& $typenow != "header"
		) {
			// TODO - clean this up
			// without this condition, users get to browse the web root
			die("Invalid browsing path.");
		}

		if (isset($_GET['feid']) && $_GET['feid'] != '') {
			$standalone = true;
			$passfeid = "&feid=".$_GET['feid'];
			$rowhlightinit =  " onload=\"rowHighlight();\"";
		} else {
			$standalone = false;
			$passfeid = '';
			$rowhlightinit =  '';	
		}

		// Assign view, thumbnail and link paths
		$browsepath = $this->_tb_config['path'][$typenow];
		$linkpath = $this->_tb_config['link'][$typenow];
		$thumbpath = $this->_tb_config[$this->_tb_config['thumbsrc']][$typenow];

		// Assign browsing options
		$sortbynow = (isset($_REQUEST['sortby']) ? $_REQUEST['sortby'] : $this->_tb_config['order']['by']);
		$sorttypenow = (isset($_REQUEST['sorttype']) ? $_REQUEST['sorttype'] : $this->_tb_config['order']['type']);
		$sorttypeflip = ($sorttypenow == 'asc' ? 'desc' : 'asc');  
		$viewtypenow = (isset($_REQUEST['viewtype']) ? $_REQUEST['viewtype'] : $this->_tb_config['view']['image']);
		$findnow = (isset($_POST['find']) && !empty($_POST['find']) ? $_POST['find'] : false);
		$showpagenow = (isset($_REQUEST['showpage']) ? $_REQUEST['showpage'] : 0);

		// Assign sort parameters for column header links
		$sortbyget = array();
		$sortbyget['name'] = '&viewtype='.$viewtypenow.'&sortby=name';
		$sortbyget['size'] = '&viewtype='.$viewtypenow.'&sortby=size'; 
		$sortbyget['type'] = '&viewtype='.$viewtypenow.'&sortby=type'; 
		$sortbyget['modified'] = '&viewtype='.$viewtypenow.'&sortby=modified';
		$sortbyget['dimensions'] = '&viewtype='.$viewtypenow.'&sortby=dimensions'; 
		$sortbyget[$sortbynow] .= '&sorttype='.$sorttypeflip;

		// Assign css style for current sort type column
		$thclass = array();
		$thclass['name'] = '';
		$thclass['size'] = '';
		$thclass['type'] = '';
		$thclass['modified'] = '';
		$thclass['dimensions'] = '';
		$thclass[$sortbynow] = ' class="'.$sorttypenow.'"';

		$notify = array();

		$newthumbqty = 0;

		// read folder contents if folder exists
		if (file_exists($this->_tb_config['docroot'].$browsepath)) {
			// Read directory contents and populate $file array
			$dh = opendir($this->_tb_config['docroot'].$browsepath);
			$file = array();
			while (($filename = readdir($dh)) !== false) {
				if($filename != "." && $filename != ".." && !is_dir($this->_tb_config['docroot'].$browsepath.$filename)) {
					// search file name if search term entered
					if($findnow) {
						$exists = stripos($filename, $findnow);
					}
					// assign file details to array, for all files or those that match search
					if (!$findnow || ($findnow && $exists !== false)) {
						$file['name'][] = $filename;
						$file['modified'][] = filemtime($this->_tb_config['docroot'].$browsepath.$filename);
						$file['size'][] = filesize($this->_tb_config['docroot'].$browsepath.$filename);

						// image specific info or general
						if (($typenow == 'image' || $typenow == 'bg_image' || $typenow == 'bg_image_thumb' || $typenow == 'cat_thumb' || $typenow == 'header') && $imginfo = getimagesize($this->_tb_config['docroot'].$browsepath.$filename)) {
							$file['width'][] = $imginfo[0];
							$file['height'][] = $imginfo[1];
							$file['dimensions'][] = $imginfo[0] + $imginfo[1];
							$file['type'][] = $imginfo['mime'];

							// Check a thumbnail exists
							if (!file_exists($this->_tb_config['docroot'].$browsepath."_thumbs/")) $this->createfolder($this->_tb_config['docroot'].$browsepath."_thumbs/", $this->_tb_config['unixpermissions']);
					  		$thumbimg = $this->_tb_config['docroot'].$browsepath."_thumbs/_".$filename;
							if (!file_exists($thumbimg)) {
								$nothumbimg = $this->_tb_config['docroot'].$browsepath.$filename;
								$mime = getimagesize($nothumbimg);
								$im = $this->convert_image($nothumbimg, $mime['mime']);
								$this->resizeimage($im, $this->_tb_config['thumbsize'], $this->_tb_config['thumbsize'], $thumbimg, $this->_tb_config['thumbquality']);
								imagedestroy($im);
								$newthumbqty++;
							}
						} else {
							$file['width'][] = 'N/A';
							$file['height'][] = 'N/A';
							$file['dimensions'][] = 'N/A';
							$file['type'][] = $this->returnMIMEType($filename);
						}
					}			
				}
			}
			closedir($dh);
		} else {
			// create file upload folder
			$success = $this->createfolder($this->_tb_config['docroot'].$browsepath, $this->_tb_config['unixpermissions']);
			if ($success) {
				if ($typenow == 'image' || $typenow == 'bg_image' || $typenow == 'bg_image_thumb' || $typenow == 'cat_thumb' || $typenow == 'header') {
					$this->createfolder($this->_tb_config['docroot'].$browsepath.'_thumbs/', $this->_tb_config['unixpermissions']);
				}
				$notify[] = array('type' => "success", 'message' => sprintf(TB_MSGMKDIR, $browsepath));
			} else {
				$notify[] = array('type' => "error", 'message' => sprintf(TB_MSGMKDIRFAIL, $browsepath));
			}
		}

		// generate alert if new thumbnails created
		if ($newthumbqty > 0) {
			$notify[] = array('type' => "info", 'message' => sprintf(TB_MSGNEWTHUMBS, $newthumbqty));
		}

		// determine sort order
		$sortorder = ($sorttypenow == 'asc' ? SORT_ASC : SORT_DESC);
		$num_of_files = (isset($file['name']) ? count($file['name']) : 0);

		if ($num_of_files > 0) {
			// sort files by selected order
			$this->sortfileorder($sortbynow, $sortorder, $file);
		}

		// determine pagination
		if($this->_tb_config['pagination'] > 0) {
			$showpage_start = ($showpagenow ? ($_REQUEST['showpage'] * $this->_tb_config['pagination']) - $this->_tb_config['pagination'] : 0);
			$showpage_end = $showpage_start + $this->_tb_config['pagination'];
			if($showpage_end > $num_of_files) {
				$showpage_end = $num_of_files;
			}
		} else {
			$showpage_start = 0;
			$showpage_end = $num_of_files;
		}

		$pagelimit = 0;
		$pagelabels = array();
		if ($this->_tb_config['pagination'] > 0) {
			$pagelimit = ceil($num_of_files / $this->_tb_config['pagination']) + 1;
			for ($i = 1; $i <= $pagelimit; $i++) {
				$pagelabels[] = $i;
			}
			$this->view->pagelimit = $pagelimit;
			$this->view->pagelabels = $pagelabels;
		}

		$browser_table = "";
		if (($typenow == 'image' || $typenow == 'bg_image' || $typenow == 'bg_image_thumb' || $typenow == 'cat_thumb' || $typenow == 'header') && $viewtypenow != "detail") {
			$browser_table .= "</table></div>";
			for ($i = $showpage_start; $i < $showpage_end; $i++) {
				$browser_table .= '<div class="img-browser">'
					.'<a href="#" onclick="selectURL(\''.$linkpath.$file['name'][$i].'\');" '
					.'title="'.TB_FILENAME.': '.$file['name'][$i]
					.'&#13;&#10;'.TB_TYPE.': '.$file['type'][$i]
					.'&#13;&#10;'.TB_SIZE.': '.$this->bytestostring($file['size'][$i], 1)
					.'&#13;&#10;'.TB_DATE.': '.date($this->_tb_config['dateformat'],$file['modified'][$i])
					.'&#13;&#10;'.TB_DIMENSIONS.': '.$file['width'][$i].' x '.$file['height'][$i]
					.'"><img src="'.$thumbpath.'_thumbs/_'.$file['name'][$i]
					.'" /><div class="filename">'.$file['name'][$i].'</div></a></div>';
			}
		} else {
			for ($i = $showpage_start; $i < $showpage_end; $i++) {
				$alt = ($this->IsOdd($i) ? 'r1' : 'r0');
				$browser_table .= '<tr class="'.$alt.'">';
				if ($typenow == 'image' || $typenow == 'bg_image' || $typenow == 'bg_image_thumb' || $typenow == 'cat_thumb' || $typenow == 'header') {
					$browser_table .= '<td><a class="imghover" href="#" onclick="selectURL(\''
						.$linkpath.$file['name'][$i].'\');" title="'.$file['name'][$i]
						.'"><img src="'.$thumbpath.'_thumbs/_'.$file['name'][$i].'" alt="" />'
						.$this->truncate_text($file['name'][$i], 30).'</a></td>';
				} else {
					$browser_table .= '<td><a href="#" onclick="selectURL(\''.$linkpath.$file['name'][$i].'\');" title="'
						.$file['name'][$i].'">'.$this->truncate_text($file['name'][$i], 30).'</a></td>';
				}
				$browser_table .= '<td>'.$this->bytestostring($file['size'][$i], 1).'</td>';
				if ($typenow == 'image' || $typenow == 'bg_image' || $typenow == 'bg_image_thumb' || $typenow == 'cat_thumb' || $typenow == 'header') {
					$browser_table .= '<td>'.$file['width'][$i].' x '.$file['height'][$i].'</td>';
				}
				$browser_table .= '<td>'.$file['type'][$i].'</td>'
					.'<td>'.date($this->_tb_config['dateformat'], $file['modified'][$i]).'</td>'
					.'</tr>'."\n";
			}
			$browser_table .= "</table></div>";
		}
		$this->view->browser_table = $browser_table;

		$this->view->tb_browse        = TB_BROWSE;
		$this->view->tb_browsefiles   = TB_BROWSEFILES;
		$this->view->tb_date          = TB_DATE;
		$this->view->tb_details       = TB_DETAILS;
		$this->view->tb_dimensions    = TB_DIMENSIONS;
		$this->view->tb_edit          = TB_EDIT;
		$this->view->tb_filename      = TB_FILENAME;
		$this->view->tb_page          = TB_PAGE;
		$this->view->tb_search        = TB_SEARCH;
		$this->view->tb_show          = TB_SHOW;
		$this->view->tb_size          = TB_SIZE;
		$this->view->tb_thumbs        = TB_THUMBS;
		$this->view->tb_type          = TB_TYPE;
		$this->view->tb_upload        = TB_UPLOAD;
		$this->view->tb_view          = TB_VIEW;
		$this->view->main_form_action = "/filebrowser/admin/tinybrowser/?type=".$typenow.$passfeid;
		$this->view->standalone       = $standalone;
		$this->view->rowhlightinit    = $rowhlightinit;
		$this->view->sortbynow        = $sortbynow;
		$this->view->sorttypenow      = $sorttypenow;
		$this->view->viewtypenow      = $viewtypenow;
		$this->view->typenow          = $typenow;
		$this->view->findnow          = $findnow;
		$this->view->pagelimit        = $pagelimit;
		$this->view->thclass          = $thclass;
		$this->view->linkpath         = $linkpath;
		$this->view->thumbpath        = $thumbpath;
		$this->view->thclass          = $thclass;
		$this->view->sortbyget        = $sortbyget;
		$this->view->showpagenow      = $showpagenow;
		$this->view->passfeid         = $passfeid;
		$this->view->passfeid1        = substr($passfeid, 1);
		$this->view->notify           = $notify;
		$this->view->tinybrowser      = $this->_tb_config;
	}

	function tinymcejsAction() {
		// TODO - THIS WILL NOT WORK - it will probably need to be hardcoded
		// $tbpath = ""; // pathinfo($_SERVER['SCRIPT_NAME']);
		$this->view->tburl = "/filebrowser/admin/tinybrowser/"; // $tbpath['dirname'].'/tinybrowser.php';
	}

	function standalonejsAction() {
		$this->view->tburl = '/filebrowser/admin/tinybrowser/';
	}

	function editAction() {

		// Assign get variables
		$typenow = (isset($_GET['type']) ? $_GET['type'] : 'image');
		$passfeid = (isset($_GET['feid']) && $_GET['feid']!='' ? '&feid='.$_GET['feid'] : '');

		// TODO - check if an array contains the value instead of doing this big if statement
		if (
			$typenow != "image"
			&& $typenow != "media"
			&& $typenow != "file"
			&& $typenow != "about_video"
			&& $typenow != "bg_image"
			&& $typenow != "bg_image_thumb"
			&& $typenow != "cat_thumb"
			&& $typenow != "header"
		) {
			// TODO - clean this up
			// without this condition, users get to browse the web root
			die("Invalid browsing path.");
		}

		// Assign edit and thumbnail path
		$editpath = $this->_tb_config['path'][$typenow];
		$thumbpath = $this->_tb_config[$this->_tb_config['thumbsrc']][$typenow];

		// Assign browsing options
		$sortbynow = (isset($_REQUEST['sortby']) ? $_REQUEST['sortby'] : $this->_tb_config['order']['by']);
		$sorttypenow = (isset($_REQUEST['sorttype']) ? $_REQUEST['sorttype'] : $this->_tb_config['order']['type']);
		$sorttypeflip = ($sorttypenow == 'asc' ? 'desc' : 'asc');  
		$viewtypenow = 'detail';
		$findnow = (isset($_POST['find']) && !empty($_POST['find']) ? $_POST['find'] : false);
		$actionnow = (isset($_POST['editaction']) ? $_POST['editaction'] : $this->_tb_config['defaultaction'] );
		$showpagenow = (isset($_REQUEST['showpage']) ? $_REQUEST['showpage'] : 0);

		// Assign sort parameters for column header links
		$sortbyget = array();
		$sortbyget['name'] = '&sortby=name';
		$sortbyget['size'] = '&sortby=size'; 
		$sortbyget['type'] = '&sortby=type'; 
		$sortbyget['created'] = '&sortby=created';
		$sortbyget['dimensions'] = '&sortby=dimensions'; 
		$sortbyget[$sortbynow] .= '&sorttype='.$sorttypeflip;

		// Assign css style for current sort type column
		$thclass = array();
		$thclass['name'] = '';
		$thclass['size'] = ''; 
		$thclass['type'] = ''; 
		$thclass['created'] = '';
		$thclass['dimensions'] = ''; 
		$thclass[$sortbynow] = ' class="'.$sorttypenow.'"';

		// Initalise alert array
		$notify = array();

		$deleteqty = 0;
		$renameqty = 0;
		$resizeqty = 0;
		$rotateqty = 0;
		$errorqty = 0;

		// Set when rotating images to force thumbnail refresh
		$imagerefresh ='';

		// TODO - this could be hacked by a logged-in user with access to this action
		// TODO - need to lock this down so you can only delete files to which you have permission

		// Delete any checked files
		if (isset($_POST['deletefile'])) {
			foreach ($_POST['deletefile'] as $delthis => $val) {
				$delthisfile = $this->_tb_config['docroot'].$editpath.$_POST['actionfile'][$delthis];
				if (file_exists($delthisfile) && unlink($delthisfile)) {
					$deleteqty++;
				} else {
					$errorqty++;
				}
				if ($typenow == 'image' || $typenow == 'bg_image' || $typenow == 'bg_image_thumb' || $typenow == 'cat_thumb' || $typenow == 'header') {
					$delthisthumb = $this->_tb_config['docroot'].$editpath."_thumbs/_".$_POST['actionfile'][$delthis];
					if (file_exists($delthisthumb)) {
						unlink($delthisthumb);
					}
				}
			}
		}

		// Rename any files with changed name
		if (isset($_POST['renamefile'])) {
			foreach ($_POST['renamefile'] as $namethis => $newname) {
				if ($_POST['actionfile'][$namethis] != $newname.$_POST['renameext'][$namethis]) {
					$namethisfilefrom = $this->_tb_config['docroot'].$editpath.$_POST['actionfile'][$namethis];
					$namethisfileto = $this->_tb_config['docroot'].$editpath.$this->clean_filename($newname.$_POST['renameext'][$namethis]);
					if (file_exists($namethisfilefrom) && rename($namethisfilefrom, $namethisfileto)) {
						$renameqty++;
					} else {
						$errorqty++;
					}
					if ($typenow == 'image' || $typenow == 'bg_image' || $typenow == 'bg_image_thumb' || $typenow == 'cat_thumb' || $typenow == 'header') {
						$namethisthumbfrom = $this->_tb_config['docroot'].$editpath."_thumbs/_".$_POST['actionfile'][$namethis];
						$namethisthumbto = $this->_tb_config['docroot'].$editpath."_thumbs/_".$this->clean_filename($newname.$_POST['renameext'][$namethis]);
						if (file_exists($namethisthumbfrom)) {
							rename($namethisthumbfrom, $namethisthumbto);
						}
					}
				}
			}
		}

		// Resize any files with new size
		if (isset($_POST['resizefile'])) {
			foreach ($_POST['resizefile'] as $sizethis => $newsize) {
				$newsize = intval($newsize);
				if ($newsize) {
					// detect silly sizes
					if ($newsize > $this->_tb_config['thumbsize']) {
						// do image resize
						$targetimg = $this->_tb_config['docroot'].$editpath.$_POST['actionfile'][$sizethis];
						if (file_exists($targetimg)) {
							$mime = getimagesize($targetimg);
							if ($_POST['resizetype'][$sizethis] == 'width') {
								$rw = $newsize;
								$rh = $mime[1];
							} else {
								$rw = $mime[0];
								$rh = $newsize;
							}
							$im = $this->convert_image($targetimg, $mime['mime']);
							$this->resizeimage($im, $rw, $rh, $targetimg, $this->_tb_config['imagequality']);
							imagedestroy($im);
							$resizeqty++;
						} else {
							$errorqty++;
						}
					} else {
						$errorqty++;
					}
				}
			}
		}

		// Rotate any selected files
		if (isset($_POST['rotatefile'])) {
			$imagerefresh = '?refresh='.uniqid('');
			foreach ($_POST['rotatefile'] as $rotatethis => $direction) {
				if ($direction != 'none') {
					$targetimg = $this->_tb_config['docroot'].$editpath.$_POST['actionfile'][$rotatethis];
					if (file_exists($targetimg)) {
						// rotate image
						if ($direction == 'clock') {
							$degree = 270;
						} else {
							$degree = 90;
						}
						$mime = getimagesize($targetimg);
						$im = $this->convert_image($targetimg, $mime['mime']);
						$newim = imagerotate($im, $degree, 0);
						imagedestroy($im);
						imagejpeg ($newim, $targetimg, $this->_tb_config['imagequality']);
						imagedestroy($newim);
						$rotateqty++;

						// delete and recreate thumbnail image
						$targetthumb = $this->_tb_config['docroot'].$editpath."_thumbs/_".$_POST['actionfile'][$rotatethis];
						if (file_exists($targetthumb)) {
							unlink($targetthumb);
						}
						$mime = getimagesize($targetimg);
						$im = $this->convert_image($targetimg, $mime['mime']);
						$this->resizeimage($im, $this->_tb_config['thumbsize'], $this->_tb_config['thumbsize'], $targetthumb, $this->_tb_config['thumbquality']);
						imagedestroy($im);
					} else {
						$errorqty++;
					}
				}
			}
		}

		// Read directory contents and populate $file array
		$dh = opendir($this->_tb_config['docroot'].$editpath);
		$file = array();
		while (($filename = readdir($dh)) !== false) {
			if ($filename != "." && $filename != ".." && !is_dir($this->_tb_config['docroot'].$editpath.$filename)) {
				// search file name if search term entered
				if ($findnow) {
					$exists = stripos($filename, $findnow);
				}

				// assign file details to array, for all files or those that match search
				if (!$findnow || ($findnow && $exists !== false)) {
					$file['name'][] = $filename;
					$file['modified'][] = filemtime($this->_tb_config['docroot'].$editpath.$filename);
					$file['size'][] = filesize($this->_tb_config['docroot'].$editpath.$filename);

					// image specific info or general
					if (($typenow == 'image' || $typenow == 'bg_image' || $typenow == 'bg_image_thumb' || $typenow == 'cat_thumb' || $typenow == 'header') && $imginfo = getimagesize($this->_tb_config['docroot'].$editpath.$filename)) {
						$file['width'][] = $imginfo[0];
						$file['height'][] = $imginfo[1];
						$file['dimensions'][] = $imginfo[0] + $imginfo[1];
						$file['type'][] = $imginfo['mime'];
					} else {
						$file['width'][] = 'N/A';
						$file['height'][] = 'N/A';
						$file['dimensions'][] = 'N/A';
						$file['type'][] = $this->returnMIMEType($filename);
					}
				}
			}
		}
		closedir($dh);

		if ($deleteqty > 0) {
			// generate alert if files deleted
			$notify['type'][] = 'success';
			$notify['message'][] = sprintf(TB_MSGDELETE, $deleteqty);
		} elseif($renameqty > 0) {
			// generate alert if files renamed
			$notify['type'][] = 'success';
			$notify['message'][] = sprintf(TB_MSGRENAME, $renameqty);
		} elseif($resizeqty > 0) {
			// generate alert if images resized
			$notify['type'][] = 'success';
			$notify['message'][] = sprintf(TB_MSGRESIZE, $resizeqty);
		} elseif($rotateqty > 0) {
			// generate alert if images rotated
			$notify['type'][] = 'success';
			$notify['message'][] = sprintf(TB_MSGROTATE, $rotateqty);
		}

		if($errorqty > 0) {
			// generate alert if file errors encountered
			$notify['type'][] = 'failure';
			$notify['message'][] = sprintf(TB_MSGEDITERR, $errorqty);
		}

		// determine sort order
		$sortorder = ($sorttypenow == 'asc' ? SORT_ASC : SORT_DESC);
		$num_of_files = (isset($file['name']) ? count($file['name']) : 0);

		if ($num_of_files > 0) {
			// sort files by selected order
			$this->sortfileorder($sortbynow, $sortorder, $file);
		}

		// determine pagination
		if ($this->_tb_config['pagination'] > 0) {
			$showpagestart = ($showpagenow ? ($_REQUEST['showpage']*$this->_tb_config['pagination'])-$this->_tb_config['pagination'] : 0);
			$showpageend = $showpagestart+$this->_tb_config['pagination'];
			if ($showpageend>$num_of_files) {
				$showpageend = $num_of_files;
			}
		} else {
			$showpagestart = 0;
			$showpageend = $num_of_files;
		}

		if ($this->_tb_config['pagination'] > 0) {
			$pagelimit = ceil($num_of_files / $this->_tb_config['pagination']) + 1;
			$pagelabels = array();
			for ($i = 1; $i <= $pagelimit; $i++) {
				$pagelabels[] = $i;
			}
		} else {
			$pagelimit = null;
			$pagelabels = null;
		}
		$this->view->pagelimit = $pagelimit;
		$this->view->pagelabels = $pagelabels;

		switch($actionnow) {
			case 'delete':
				$actionhead = TB_DELETE;
				break;
			case 'rename':
				$actionhead = TB_RENAME;
				break;
			case 'resize':
				$actionhead = TB_RESIZE;
				break;
			case 'rotate':
				$actionhead = TB_ROTATE;
				break;
			default:
				// do nothing
		}

		if ($typenow == 'image' || $typenow == 'bg_image' || $typenow == 'bg_image_thumb' || $typenow == 'cat_thumb' || $typenow == 'header') {
			$selectresize = array(
				array('width', TB_WIDTH),
				array('height', TB_HEIGHT)
			);
		}

		$file_browser_table = "";

		for ($i = $showpagestart; $i < $showpageend; $i++) {
			$alt = ($this->IsOdd($i) ? 'r1' : 'r0');
			$file_browser_table .= '<tr class="'.$alt.'">';
			if ($typenow == 'image' || $typenow == 'bg_image' || $typenow == 'bg_image_thumb' || $typenow == 'cat_thumb' || $typenow == 'header') {
				$file_browser_table .= '<td><a class="imghover" href="#" onclick="return false;" title="'.$file['name'][$i].'&#13;&#10;'.TB_DATE.': '.date($this->_tb_config['dateformat'],$file['modified'][$i]).'&#13;&#10;'.TB_DIMENSIONS.': '.$file['width'][$i].' x '.$file['height'][$i].'"><img src="'.$thumbpath.'_thumbs/_'.$file['name'][$i].$imagerefresh.'" alt="" />' .$this->truncate_text($file['name'][$i],30).'</a></td>';
			} else {
				$file_browser_table .= '<td title="'.$file['name'][$i].'&#13;&#10;'.TB_DATE.': '.date($this->_tb_config['dateformat'],$file['modified'][$i]).'">'.$this->truncate_text($file['name'][$i],30).'</td>';
			}
			$file_browser_table .= '<td>'.$this->bytestostring($file['size'][$i],1).'</td><td>'.$file['type'][$i].'</td><td>';
			$file_browser_table .= $this->form_hidden_input('actionfile['.$i.']',$file['name'][$i]);
			switch($actionnow) {
				case 'delete':
					$file_browser_table .= '<input class="del" type="checkbox" name="deletefile['.$i.']" value="1" />';	
					break;
				case 'rename':
					$ext = '.'.end(explode('.',$file['name'][$i]));
					$file_browser_table .= $this->form_hidden_input('renameext['.$i.']', $ext);
					$file_browser_table .= $this->form_text_input('renamefile['.$i.']', false, basename($file['name'][$i], $ext), 30, 120); echo $ext;
					break;
				case 'resize':
					$file_browser_table .= $this->form_text_input('resizefile['.$i.']', false, '', 4, 4); $this->form_select($selectresize, 'resizetype['.$i.']', false, '', false);
					break;
				case 'rotate':
					$file_browser_table .= '<img src="img/rotate_c.gif" alt="'.TB_ROTATECW.'" /><input class="rad" type="radio" name="rotatefile['.$i.']" value="clock"><img src="img/rotate_ac.gif" alt="'.TB_ROTATECCW.'" /><input class="rad" type="radio" name="rotatefile['.$i.']" value="anticlock">'.TB_NONE.'<input class="rad" type="radio" name="rotatefile['.$i.']" value="none" checked>';
					break;
				default:
					// do nothing
			}
			$file_browser_table .= "</td></tr>";
		}

		$file_browser_table .= "</table></div><div class=\"pushright\">";

		if ($this->_tb_config['allowdelete']) {
			$file_browser_table .= $this->form_hidden_input('sortby', $sortbynow);
			$file_browser_table .= $this->form_hidden_input('sorttype', $sorttypenow);
			$file_browser_table .= $this->form_hidden_input('find', $findnow);
			$file_browser_table .= $this->form_hidden_input('showpage', $showpagenow);
			$file_browser_table .= $this->form_hidden_input('editaction', $actionnow);
			$file_browser_table .= $this->form_submit_button('committ', $actionhead.' '.TB_FILES, 'edit');
		}

		$this->view->file_browser_table = $file_browser_table;

		$this->view->tb_action = TB_ACTION;
		$this->view->tb_browse = TB_BROWSE;
		$this->view->tb_date = TB_DATE;
		$this->view->tb_delete = TB_DELETE;
		$this->view->tb_edit = TB_EDIT;
		$this->view->tb_editfiles = TB_EDITFILES;
		$this->view->tb_filename = TB_FILENAME;
		$this->view->tb_files = TB_FILES;
		$this->view->tb_height = TB_HEIGHT;
		$this->view->tb_none = TB_NONE;
		$this->view->tb_page = TB_PAGE;
		$this->view->tb_rename = TB_RENAME;
		$this->view->tb_resize = TB_RESIZE;
		$this->view->tb_rotate = TB_ROTATE;
		$this->view->tb_rotateccw = TB_ROTATECCW;
		$this->view->tb_rotatecw = TB_ROTATECW;
		$this->view->tb_search = TB_SEARCH;
		$this->view->tb_show = TB_SHOW;
		$this->view->tb_size = TB_SIZE;
		$this->view->tb_type = TB_TYPE;
		$this->view->tb_upload = TB_UPLOAD;
		$this->view->tb_width = TB_WIDTH;

		$this->view->edit_form_action = '/filebrowser/admin/edit/?type='.$typenow.$passfeid;
		$this->view->action_form_action = '/filebrowser/admin/edit/?type='.$typenow.$passfeid;
		$this->view->actionhead = $actionhead;
		$this->view->actionnow = $actionnow;
		$this->view->findnow = $findnow;
		$this->view->sorttypenow = $sorttypenow;
		$this->view->sortbynow = $sortbynow;
		$this->view->typenow = $typenow;
		$this->view->notify = $notify;
		$this->view->passfeid = $passfeid;
		$this->view->tinybrowser = $this->_tb_config;
	}

	function uploadAction() {

		// Assign get variables
		$typenow = (isset($_GET['type']) ? $_GET['type'] : 'image');
		$passfeid = (isset($_GET['feid']) && $_GET['feid']!='' ? '&feid='.$_GET['feid'] : '');

		// TODO - check if an array contains the value instead of doing this big if statement
		if (
			$typenow != "image"
			&& $typenow != "media"
			&& $typenow != "file"
			&& $typenow != "about_video"
			&& $typenow != "bg_image"
			&& $typenow != "bg_image_thumb"
			&& $typenow != "cat_thumb"
			&& $typenow != "header"
		) {
			// TODO - clean this up
			// without this condition, users get to browse the web root
			die("Invalid browsing path.");
		}

		// determine file dialog file types
		switch ($_GET['type']) {
			case 'image':
				$filestr = TB_TYPEIMG;
				break;
			case 'media':
				$filestr = TB_TYPEMEDIA;
				break;
			case 'file':
				$filestr = TB_TYPEFILE;
				break;
			case 'file':
				$filestr = TB_TYPEABOUTVIDEO;
				break;
			default:
				$filestr = TB_TYPEIMG;
				break;
		}
		$fileexts = str_replace(",", ";", $this->_tb_config['filetype'][$_GET['type']]);
		$filelist = $filestr.' ('.$this->_tb_config['filetype'][$_GET['type']].')';

		$notify = array();

		$goodqty = (isset($_GET['goodfiles']) ? $_GET['goodfiles'] : 0);
		$badqty = (isset($_GET['badfiles']) ? $_GET['badfiles'] : 0);
		$dupqty = (isset($_GET['dupfiles']) ? $_GET['dupfiles'] : 0);

		if ($goodqty > 0) {
			$notify[] = array('type' => "success", 'message' => sprintf(TB_MSGUPGOOD, $goodqty));
		}
		if ($badqty > 0) {
			$notify[] = array('type' => "failure", 'message' => sprintf(TB_MSGUPBAD, $badqty));
		}
		if ($dupqty > 0) {
			$notify[] = array('type' => "failure", 'message' => sprintf(TB_MSGUPDUP, $dupqty));
		}
		if (isset($_GET['permerror'])) {
			$notify[] = array('type' => "failure", 'message' => sprintf(TB_MSGUPFAIL, $this->_tb_config['docroot'].$this->_tb_config['path'][$typenow]));
		}

		$this->view->tb_filename    = TB_FILENAME;
		$this->view->tb_size        = TB_SIZE;
		$this->view->tb_type        = TB_TYPE;
		$this->view->tb_progress    = TB_PROGRESS;
		$this->view->tb_browse      = TB_BROWSE;
		$this->view->tb_remove      = TB_REMOVE;
		$this->view->tb_upload      = TB_UPLOAD;
		$this->view->tb_edit        = TB_EDIT;
		$this->view->tb_uploadfiles = TB_UPLOADFILES;
		$this->view->tb_uploadafile = TB_UPLOADAFILE;
		$this->view->tb_msgmaxsize  = TB_MSGMAXSIZE;
		$this->view->tb_ttlmaxsize  = TB_TTLMAXSIZE;
		$this->view->tb_bytes       = TB_BYTES;
		$this->view->obfuscate      = md5($_SERVER['DOCUMENT_ROOT'].$this->_tb_config['obfuscate']);
		$this->view->path           = urlencode($this->_tb_config['path'][$typenow]);
		$this->view->maxsize        = $this->_tb_config['maxsize'][$_GET['type']];
		$this->view->session_id     = session_id();
		$this->view->filelist       = $filelist;
		$this->view->fileexts       = $fileexts;
		$this->view->typenow        = $typenow;
		$this->view->notify         = $notify;
		$this->view->passfeid       = $passfeid;
		$this->view->tinybrowser    = $this->_tb_config;
	}

	function uploadfileAction() {

		// Check hash is correct (workaround for Flash session bug, to stop external form posting)
		if ($_GET['obfuscate'] != md5($_SERVER['DOCUMENT_ROOT'].$this->_tb_config['obfuscate'])) {
			echo 'Error!';
			exit;
		}
		// Check  and assign get variables
		if (isset($_GET['type'])) {
			$typenow = $_GET['type'];
		} else {
			echo 'Error!';
			exit;
		}
		if (isset($_GET['folder'])) {
			$dest_folder = urldecode($_GET['folder']);
		} else {
			echo 'Error!';
			exit;
		}
		// Check file extension isn't prohibited
		$ext = end(explode('.', $_FILES['Filedata']['name']));
		if (!$this->validateExtension($ext, $this->_tb_config['prohibited'])) {
			echo 'Error!';
			exit;
		}
		// Check file data
		if ($_FILES['Filedata']['tmp_name'] && $_FILES['Filedata']['name']) {
			$source_file = $_FILES['Filedata']['tmp_name'];
			$file_name = stripslashes($_FILES['Filedata']['name']);
			if (is_dir($this->_tb_config['docroot'].$folder_name.$dest_folder)) {
				$success = copy($source_file, $this->_tb_config['docroot'].$dest_folder.'/'.$file_name.'_');
			}
			if ($success) {
				header('HTTP/1.1 200 OK');
				// if the above doesn't work for you,
				// try header('HTTP/1.1 201 Created');
			} else {
				echo 'Error!';
				exit;
			}
		}
	}

	function uploadprocessAction() {
		$request = new Cts_Request($this->getRequest());

		$passfeid = "";
		if ($request->has('feid')) {
			$passfeid = "&feid=".$request->feid;
		}

		if (!$this->getRequest()->isPost()) {
        	$this->_redirect("/default/auth/missing");
		} else {
			if (!array_key_exists('filedata', $_FILES)) {
        		$this->_redirect("/default/auth/missing");
			} else {
				if ($_FILES['filedata']['tmp_name'] != '') {
					move_uploaded_file($_FILES['filedata']['tmp_name'],
						$this->_tb_config['docroot'].$this->_tb_config['path'][$request->type]."/".$_FILES['filedata']['name']);
					Users::clearUserCache("black-diamond");
	        		$this->_redirect('/filebrowser/admin/upload/?type='.$request->type.$passfeid.'&badfiles=0&goodfiles=1&dupfiles=0');
				} else {
					$this->_redirect('/filebrowser/admin/upload/?type='.$request->type.$passfeid.'&permerror=1&total=1');
				}
			}
		}

		// // Initialise files array and error vars
		// $files = array();
		// $good = 0;
		// $bad = 0;
		// $dup = 0;
		// $total = (isset($_GET['filetotal']) ? $_GET['filetotal'] : 0);
		// 
		// // Assign get variables
		// $folder = $this->_tb_config['docroot'].urldecode($_GET['folder']);
		// $passfeid = (isset($_GET['feid']) ? '&feid='.$_GET['feid'] : '');
		// 
		// Cts_Log::report("Filebrowser: Upload: Attempting to create filesystem handle.", null, Zend_Log::INFO);
		// if ($handle = opendir($folder)) {
		// 	Cts_Log::report("Filebrowser: Upload: Filesystem handle successfully created.", null, Zend_Log::INFO);
		// 	while (false !== ($file = readdir($handle))) {
		// 		if ($file != "." && $file != ".." && substr($file, -1) == '_') {
		// 
		// 			//-- File Naming
		// 			$tmp_filename = $folder.$file;
		// 			$dest_filename = $folder.rtrim($file, '_');
		// 
		// 			//-- Duplicate Files
		// 			if (file_exists($dest_filename)) {
		// 				unlink($tmp_filename);
		// 				$dup++;
		// 				continue;
		// 			}
		// 
		// 			//-- Bad extensions
		// 			$ext = end(explode('.', $dest_filename));
		// 			if (!$this->validateExtension($ext, $this->_tb_config['prohibited'])) {
		// 				unlink($tmp_filename);
		// 				continue;
		// 			}
		// 
		// 			//-- Rename temp file to dest file
		// 			rename($tmp_filename, $dest_filename);
		// 			$good++;
		// 
		// 			//-- if image, perform additional processing
		// 			if ($_GET['type'] == 'image') {
		// 				//-- Good mime-types
		// 				$imginfo = getimagesize($dest_filename);
		// 				if ($imginfo === false) {
		// 					unlink($dest_filename);
		// 					continue;
		// 				}
		// 				$mime = $imginfo['mime'];
		// 
		// 				// resize image to maximum height and width, if set
		// 				if ($this->_tb_config['imageresize']['width'] > 0 || $this->_tb_config['imageresize']['height'] > 0) {
		// 					// assign new width and height values, only if they are less than existing image size
		// 					$widthnew = ($this->_tb_config['imageresize']['width'] > 0 && $this->_tb_config['imageresize']['width'] < $imginfo[0] ? $this->_tb_config['imageresize']['width'] : $imginfo[0]);
		// 					$heightnew = ($this->_tb_config['imageresize']['height'] > 0 && $this->_tb_config['imageresize']['height'] < $imginfo[1] ? $this->_tb_config['imageresize']['height'] :  $imginfo[1]);
		// 
		// 					// only resize if width or height values are different
		// 					if ($widthnew != $imginfo[0] || $heightnew != $imginfo[1]) {
		// 						$im = $this->convert_image($dest_filename, $mime);
		// 						$this->resizeimage($im, $widthnew, $heightnew, $dest_filename, $this->_tb_config['imagequality']);
		// 						imagedestroy($im);
		// 					}
		// 				}
		// 
		// 				// generate thumbnail
		// 				$thumbimg = $folder."_thumbs/_".rtrim($file, '_');
		// 				if (!file_exists($thumbimg)) {
		// 					$im = $this->convert_image($dest_filename, $mime);
		// 					$this->resizeimage($im, $this->_tb_config['thumbsize'], $this->_tb_config['thumbsize'], $thumbimg, $this->_tb_config['thumbquality']);
		// 					imagedestroy($im);
		// 				}
		// 			}
		// 		}
		// 	}
		// 	closedir($handle);
		// }
		// $bad = $total - ($good + $dup);
		// 
		// // Check for problem during upload
		// if ($total > 0 && $bad == $total) {
		// 	Header('Location: /filebrowser/admin/upload/?type='.$_GET['type'].$passfeid.'&permerror=1&total='.$total);
		// } else {
		// 	Header('Location: /filebrowser/admin/upload/?type='.$_GET['type'].$passfeid.'&badfiles='.$bad.'&goodfiles='.$good.'&dupfiles='.$dup);
		// }
	}

	// SUPPORTING FUNCTIONS

	// TODO - make sure all calls to these supporting functions use $this->funcName()

	function createfolder($dir, $perm) {
		if (mkdir($dir, $perm)) {
			chmod($dir, $perm);
			return true;	
		}
		else {
			return false;
		}
	}

	function validateExtension($extension, $types) {
		if (in_array($extension, $types)) {
			return false;
		} else {
			return true;
		}
	}

	function sortfileorder(&$sortbynow, &$sortorder, &$file) {
		switch($sortbynow) {
			case 'name':
				array_multisort($file['name'], $sortorder, $file['type'], $sortorder, $file['modified'], $sortorder, $file['size'], $sortorder, $file['dimensions'], $sortorder, $file['width'], $sortorder, $file['height'], $sortorder);
				break;
			case 'size':
				array_multisort($file['size'], $sortorder, $file['name'], SORT_ASC, $file['type'], $sortorder, $file['modified'], $sortorder, $file['dimensions'], $sortorder, $file['width'], $sortorder, $file['height'], $sortorder);
				break;
			case 'type':
				array_multisort($file['type'], $sortorder, $file['name'], SORT_ASC, $file['size'], $sortorder, $file['modified'], $sortorder, $file['dimensions'], $sortorder, $file['width'], $sortorder, $file['height'], $sortorder);
				break;
			case 'modified':
				array_multisort($file['modified'], $sortorder, $file['name'], $sortorder, $file['type'], $sortorder, $file['size'], $sortorder, $file['dimensions'], $sortorder, $file['width'], $sortorder, $file['height'], $sortorder);
				break;
			case 'dimensions':
				array_multisort($file['dimensions'], $sortorder, $file['width'], $sortorder, $file['name'], SORT_ASC, $file['modified'], $sortorder, $file['type'], $sortorder, $file['size'], $sortorder, $file['height'], $sortorder);
				break;
			default:
				// do nothing
		}
	}

	function resizeimage($im, $maxwidth, $maxheight, $urlandname, $comp) {
		$width = imagesx($im);
		$height = imagesy($im);
		if (($maxwidth && $width > $maxwidth) || ($maxheight && $height > $maxheight)) {
			if ($maxwidth && $width > $maxwidth) {
				$widthratio = $maxwidth/$width;
				$resizewidth=true;
			} else {
				$resizewidth=false;
			}
			if ($maxheight && $height > $maxheight) {
				$heightratio = $maxheight / $height;
				$resizeheight = true;
			} else {
				$resizeheight = false;
			}
			if ($resizewidth && $resizeheight) {
				if ($widthratio < $heightratio) {
					$ratio = $widthratio;
				} else {
					$ratio = $heightratio;
				}
			} elseif($resizewidth) {
				$ratio = $widthratio;
			} elseif($resizeheight) {
				$ratio = $heightratio;
			}
			$newwidth = $width * $ratio;
			$newheight = $height * $ratio;
			if(function_exists("imagecopyresampled")) {
				$newim = imagecreatetruecolor($newwidth, $newheight);
				imagecopyresampled($newim, $im, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
			} else {
				$newim = imagecreate($newwidth, $newheight);
				imagecopyresized($newim, $im, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
			}
			imagejpeg ($newim, $urlandname, $comp);
			imagedestroy ($newim);
		} else {
			imagejpeg ($im, $urlandname, $comp);
		}
	}

	function convert_image($imagetemp, $imagetype) {
		if ($imagetype == "image/pjpeg" || $imagetype == "image/jpeg") {
			$cim1 = imagecreatefromjpeg($imagetemp);
		} elseif ($imagetype == "image/x-png" || $imagetype == "image/png") {
			$cim1 = imagecreatefrompng($imagetemp);
		} elseif ($imagetype == "image/gif") {
			$cim1 = imagecreatefromgif($imagetemp);
		}
		return $cim1;
	}

	function form_select($options, $name, $label, $current, $auto) {
		$output = "";
		if ($label) {
			$output .= "<label for=\"".$name."\">".$label."</label>";
		} 
		$output .= "<select name=\"".$name."\"";
		if ($auto) {
			$output .= " onchange=\"this.form.submit();\"";
		}
		$output .= ">";
		$loopnum = count($options); 
		for ($i = 0; $i < $loopnum; $i++) {
			$selected = ($options[$i][0] == $current ? ' selected' : '');
			$output .= "<option value=\"".$options[$i][0]."\"".$selected.">".$options[$i][1]."</option>";
		}
		$output .= "</select>";
		return $output;
	}

	function form_hidden_input($name, $value) {
		return "<input type=\"hidden\" name=\"".$name."\" value=\"".$value."\" />";
	}

	function form_text_input($name, $label, $value, $size, $maxlength) {
		$output = "";
		if ($label) {
			$output .= "<label for=\"".$name."\">".$label."</label>";
		}
		$output .= "<input type=\"text\" name=\"".$name."\" size=\"".$size."\" maxlength=\"".$maxlength."\" value=\"".$value."\" />";
		return $output;
	}

	function form_submit_button($name, $label, $class) {
		$output = "<button ";
		if ($class) {
			$output .= "class=\"".$class."\" ";
		}
		$output .= "type=\"submit\" name=\"".$name."\">".$label."</button></form>";
		return $output;
		// <button class="" type="submit" name=""></button></form>
	}

	function IsOdd($num) {
		return (1 - ($num & 1));
	}

	function truncate_text($textstring, $length) {
		if (strlen($textstring) > $length) {
			$textstring = substr($textstring, 0, $length).'...';
		}
		return $textstring;
	}

	function bytestostring($size, $precision = 0) {
	    $sizes = array('YB', 'ZB', 'EB', 'PB', 'TB', 'GB', 'MB', 'KB', 'B');
	    $total = count($sizes);
	    while($total-- && $size > 1024) $size /= 1024;
	    return round($size, $precision).' '.$sizes[$total];
	}

	function clean_filename($filename) {
		$reserved = preg_quote('\/:*?"<>|', '/');//characters that are  illegal on any of the 3 major OS's and other strang characters
		return preg_replace("/([\\x00-\\x20\\x7f-\\xff{$reserved}])/e", "_", $filename);
	}

	function returnMIMEType($filename) {
		preg_match("|\.([a-z0-9]{2,4})$|i", $filename, $fileSuffix);
		switch(strtolower($fileSuffix[1])) {
			case "js" :
				return "application/x-javascript";
			case "json" :
				return "application/json";
			case "jpg" :
			case "jpeg" :
			case "jpe" :
				return "image/jpg";
			case "png" :
			case "gif" :
			case "bmp" :
			case "tiff" :
				return "image/".strtolower($fileSuffix[1]);
			case "css" :
				return "text/css";
			case "xml" :
				return "application/xml";
			case "doc" :
			case "docx" :
				return "application/msword";
			case "xls" :
			case "xlt" :
			case "xlm" :
			case "xld" :
			case "xla" :
			case "xlc" :
			case "xlw" :
			case "xll" :
				return "application/vnd.ms-excel";
			case "ppt" :
			case "pps" :
				return "application/vnd.ms-powerpoint";
			case "rtf" :
				return "application/rtf";
			case "pdf" :
				return "application/pdf";
			case "html" :
			case "htm" :
			case "php" :
				return "text/html";
			case "txt" :
				return "text/plain";
			case "mpeg" :
			case "mpg" :
			case "mpe" :
				return "video/mpeg";
			case "mp3" :
				return "audio/mpeg3";
			case "wav" :
				return "audio/wav";
			case "aiff" :
			case "aif" :
				return "audio/aiff";
			case "avi" :
				return "video/msvideo";
			case "wmv" :
				return "video/x-ms-wmv";
			case "mov" :
				return "video/quicktime";
			case "zip" :
				return "application/zip";
			case "tar" :
				return "application/x-tar";
			case "swf" :
				return "application/x-shockwave-flash";
			case "flv" :
				return "video/x-flv";
			default :
				if (function_exists("mime_content_type")) {
					$fileSuffix = mime_content_type($filename);
				}
				return "unknown/" . trim($fileSuffix[0], ".");
		}

	}

}
